package com.gitee.faster.webdav.kernel.protocol.filter;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.gitee.faster.webdav.common.constant.Constants;
import com.gitee.faster.webdav.common.constant.HttpHeaderEnum;
import com.gitee.faster.webdav.kernel.Configuration;
import com.gitee.faster.webdav.kernel.protocol.HttpExchange;
import lombok.extern.slf4j.Slf4j;
import org.smartboot.http.common.enums.HttpStatus;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * Basic 权限过滤器
 *
 * @author hongda.li
 */
@Slf4j
public class HttpFilterAuthorization implements HttpFilter {
    /**
     * 优先级
     */
    public static final int ORDER = Integer.MIN_VALUE + 100;

    /**
     * 配置文件中指定的合法授权码集合
     */
    private final String authorization;

    public HttpFilterAuthorization() {
        Configuration configuration = Configuration.getInstance();
        String username = configuration.getUsername();
        String password = configuration.getPassword();
        if (username == null || password == null) {
            this.authorization = null;
        } else {
            byte[] bytes = (username + StrPool.COLON + password).getBytes(StandardCharsets.UTF_8);
            this.authorization = Constants.BASIC_PREFIX + Base64.getEncoder().encodeToString(bytes);
        }
    }

    @Override
    public int order() {
        return ORDER;
    }

    @Override
    public boolean doNext(HttpExchange httpExchange) {
        // Basic : Base64(username:password)
        String authorization = httpExchange.getHeaderValue().getStr(HttpHeaderEnum.AUTHORIZATION.getHeader());

        if (this.authorization == null) {
            log.debug("跳过权限验证");
            return true;
        }

        if (Objects.equals(this.authorization, authorization)) {
            log.debug("通过权限验证 : {}", authorization);
            return true;
        }

        log.debug("无权限访问 : {}", ObjectUtil.defaultIfNull(authorization, StrUtil.EMPTY));

        // WWW-Authenticate : Basic realm="FasterWebDavServer"
        httpExchange.addHeader(HttpHeaderEnum.WWW_AUTHENTICATE.getHeader(), Constants.BASIC_REALM_VALUE);

        // 401
        httpExchange.setHttpStatus(HttpStatus.UNAUTHORIZED);

        return false;
    }
}
